import Foundation
import AppKit

class WallpaperPreset {
    static let shared = WallpaperPreset()
    
    struct Preset: Codable {
        let id: UUID
        let name: String
        let wallpapers: [DisplayWallpaper]
        let createdAt: Date
        var isFavorite: Bool
    }
    
    struct DisplayWallpaper: Codable {
        let displayID: String  // 使用NSScreen的deviceDescription中的NSScreenNumber作为标识
        let wallpaperURL: URL
        let isVideo: Bool
        let volume: Float?
        let isMuted: Bool?
    }
    
    private var presets: [Preset] = []
    private let presetsURL: URL
    
    private init() {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        presetsURL = documentsDirectory.appendingPathComponent("wallpaper_presets.json")
        loadPresets()
    }
    
    private func loadPresets() {
        guard let data = try? Data(contentsOf: presetsURL) else { return }
        presets = (try? JSONDecoder().decode([Preset].self, from: data)) ?? []
    }
    
    private func savePresets() {
        guard let data = try? JSONEncoder().encode(presets) else { return }
        try? data.write(to: presetsURL)
    }
    
    func createPreset(name: String, wallpapers: [DisplayWallpaper]) -> Preset {
        let preset = Preset(
            id: UUID(),
            name: name,
            wallpapers: wallpapers,
            createdAt: Date(),
            isFavorite: false
        )
        presets.append(preset)
        savePresets()
        return preset
    }
    
    func deletePreset(_ preset: Preset) {
        presets.removeAll { $0.id == preset.id }
        savePresets()
    }
    
    func toggleFavorite(_ preset: Preset) {
        if let index = presets.firstIndex(where: { $0.id == preset.id }) {
            presets[index].isFavorite.toggle()
            savePresets()
        }
    }
    
    func getAllPresets() -> [Preset] {
        return presets
    }
    
    func getFavoritePresets() -> [Preset] {
        return presets.filter { $0.isFavorite }
    }
    
    func applyPreset(_ preset: Preset) {
        for wallpaper in preset.wallpapers {
            guard let screen = NSScreen.screens.first(where: { 
                ($0.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? UInt32)?.description == wallpaper.displayID 
            }) else { continue }
            
            try? DisplayManager.shared.setWallpaper(url: wallpaper.wallpaperURL, isVideo: wallpaper.isVideo, for: screen)
            
            if wallpaper.isVideo {
                if let volume = wallpaper.volume {
                    DisplayManager.shared.setVolume(volume, for: screen)
                }
                if let isMuted = wallpaper.isMuted {
                    if isMuted {
                        DisplayManager.shared.toggleMute(for: screen)
                    }
                }
            }
        }
    }
}